
package com.scalar.chiptrack.users.actions;

import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.users.forms.UserProfileForm;
import com.scalar.chiptrack.utils.ConfigManager;

public class UserProfileAction extends ChipTrackAction {

    private static String SOURCE_PAGE = "/userProfile.do";  // this class

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {
                                      
        HttpSession session = request.getSession();
        User user = null;
        
        if ((user = (User) session.getAttribute (SessionKeys.USER_KEY)) == null) {
            ActionForward actionForward = new ActionForward (ConfigManager.getDefaultLoginPage() + "?sourcePage=" + SOURCE_PAGE);
            return actionForward;
        }
               
        UserProfileForm profileForm = null; 
        
        String action = request.getParameter("action");
        if (action == null) {
            action = "show";
        }
               
        if (action.equalsIgnoreCase("save") == true) {
            
            profileForm = (UserProfileForm) form;

            // Validate the form and return if there are any errors
            HashMap errors = validate (profileForm);
            if (errors != null) {
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
                return (mapping.findForward("failure"));
            }

            DBTransaction dbTransaction = null;
            boolean success = false;
            
            try {
                // Start transaction 
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();

                // Update user -- both in database and in session
                
                UserDAO.updateUserProfile (dbTransaction, 
                                             user.getUserId(), 
                                             profileForm.getOldPassword(), 
                                             profileForm.getNewPassword(), 
                                             profileForm.getFirstName(), 
                                             profileForm.getLastName(), 
                                             profileForm.getPhoneNumber(), 
                                             profileForm.getFaxNumber(), 
                                             profileForm.getEmail(),
                                             profileForm.getReceiveNotifications());
                
                user.setEmail (profileForm.getEmail());

                // Update address
                Address address = new Address (profileForm.getAddress1(),
                                                profileForm.getAddress2(),
                                                profileForm.getCity(),
                                                profileForm.getState(),
                                                profileForm.getCountry(),
                                                profileForm.getZipCode());

                address.setAddressId (user.getAddressId());

                UserDAO.updateAddress (dbTransaction, address);
                System.out.println ("updating address.. " + address);

                HashMap info = new HashMap();
                info.put ("User profile has been saved successfully", null);
                request.setAttribute (SessionKeys.INFO_MESSAGES, info);
                
                success = true;
                // End transaction 
            } 
            catch (ScalarException se) {
                // Exception while updating user profile
                // log it
                se.printStackTrace();
                errors = new HashMap();
                errors.put ("Internal Server Error", "Could not update the profile");
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            finally {
                // Rollback or Commit the Transaction
            
                if (success == true) {
                    dbTransaction.commit();
                }
                else {
                    dbTransaction.rollback();
                }
            }
            
            if (success) {
                return (mapping.findForward ("success"));
            }
            
            return (mapping.findForward ("failure"));
        }
        
        System.out.println ("Showing profile for " + user.getUserId());

        profileForm = new UserProfileForm();
        profileForm.setFirstName (user.getFirstName());
        profileForm.setLastName (user.getLastName());
        profileForm.setPhoneNumber (user.getPhoneNumber());
        profileForm.setFaxNumber (user.getFaxNumber());
        profileForm.setEmail (user.getEmail());
        profileForm.setReceiveNotifications (user.getReceiveNotifications());

        Address address = null;
        boolean success = false;
        try {
            address = UserDAO.loadAddressById (user.getAddressId());
            success = true;
        }
        catch (ScalarException se) {
            HashMap errors = new HashMap();
            errors.put ("Internal Server Error", "Could not load Address Information");
            request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
        }
        
        if (success == false) {
            return (mapping.findForward ("failure"));
        }
        
        if (address != null) {
            profileForm.setAddress1 (address.getAddress1());
            profileForm.setAddress2 (address.getAddress2());
            profileForm.setCity (address.getCity());
            profileForm.setState (address.getState());
            profileForm.setCountry (address.getCountry());
            profileForm.setZipCode (address.getZipCode());
        }

        request.setAttribute("userProfileForm", profileForm);       
        return (mapping.findForward("success"));

    }
    
    private HashMap validate (UserProfileForm form) {
        
        HashMap errors = new HashMap();

        String newPassword = form.getNewPassword();
        String newPassword1 = form.getNewPassword1();
        
        if (newPassword != null) {
            if (newPassword.equals(newPassword1) == false) {
                errors.put ("New Password", "Repeated password does not match with New Password");
            }
        }
        
        String firstName = form.getFirstName();
        if ((firstName == null) || (firstName.trim().length() == 0)) {
            errors.put ("First Name", "First Name required");
        }
        
        String lastName = form.getLastName();
        if ((lastName == null) || (lastName.trim().length() == 0)) {
            errors.put ("Last Name", "Last Name required");
        }
        
        String phoneNumber = form.getPhoneNumber();
        if ((phoneNumber == null) || (phoneNumber.trim().length() == 0)) {
            errors.put ("Phone Number", "Phone Number required");
        }
        else if (phoneNumber.trim().length() != 10) {
            errors.put ("Phone Number", "Invalid Phone Number");
        }
        
        
        String faxNumber = form.getFaxNumber();
        if ((faxNumber != null) && (faxNumber.trim().length() != 0) && (faxNumber.trim().length() != 10)) {
            errors.put ("Fax Number", "Invalid Fax Number");
        }
        
        String email = form.getEmail();
        if ((email == null) || (email.trim().length() == 0) || (email.indexOf("@") == -1)) {
            errors.put ("Email", "Invalid Email");
        }
        
        String address1 = form.getAddress1();
        if ((address1 == null) || (address1.trim().length() == 0)) {
            errors.put ("Address1", "Address1 Required");
        }
        
        String city = form.getCity();
        if ((city == null) || (city.trim().length() == 0)) {
            errors.put ("City", "City Required");
        }
        
        String state = form.getState();
        if ((state == null) || (state.trim().length() == 0)) {
            errors.put ("State", "State Required");
        }
        
        String country = form.getCountry();
        if ((country == null) || (country.trim().length() == 0)) {
            errors.put ("Country", "Country Required");
        }
        
        String zip = form.getZipCode();
        if ((zip == null) || (zip.trim().length() == 0)) {
            errors.put ("Zipcode", "Zip Code Required");
        }
        else {
            try { Integer.parseInt(zip); }
            catch (NumberFormatException nfe) { errors.put ("Zip Code", "Invalid Zip code"); }
        }
        
        if (!errors.isEmpty()) {
            return errors;
        }
        
        return null;
    }

}